package auth

import (
	"fmt"
	"github.com/gomodule/redigo/redis"
	"math/rand"
	"time"
	"week13/errors"
	"week13/internal/biz/agent"
	"week13/internal/data"
	"week13/internal/tool"
	"week13/metrics"
)

type  Authenticate struct {
}
func NewAuthenticate() Authenticate{
	return Authenticate{}
}
//API token 获取
func (auth  Authenticate) Token(agentId int64,secret string) (string,error) {
	agentDo, err := agent.FindAgentDo(agentId)
	if err != nil {
		return "",err
	}
	if  agentDo.Secret != secret {
		return "", errors.NewTokenFail()
	}
	r := rand.Intn(100000)  //生成0-99之间的随机数
	token := tool.SHA1(fmt.Sprintf("%s%d%d",secret,time.Now().Unix(),r))
	client, err := data.RedisClient()
	if err != nil {
		return "", err
	}
	defer client.Close()
	_, err =client.Do("set",token,agentId,"EX",3600*2)
	if err != nil {
		metrics.IncrServerRequest("Token",errors.CACHE_ERROR)
		return "", errors.NewExecuteFail("redis set token error")
	}
	return token,nil
}
//渠道 token 鉴权
func (auth  Authenticate) Auth(token string) (int64,error){
	client, err := data.RedisClient()
	if err != nil {
		return 0, err
	}
	defer client.Close()
	agentId, err := redis.Int64(client.Do("GET",token))
	if err != nil {
		metrics.IncrServerRequest("Auth",errors.CACHE_ERROR)
		return 0, errors.NewExecuteFail("redis get token error")
	}

	return agentId,nil
}